package com.inspur.edp.ai.flow.node;

import com.fasterxml.jackson.databind.JsonNode;
import com.inspur.edp.ai.flow.engine.FlowContext;
import com.inspur.edp.ai.flow.engine.strategy.DefaultFlowStrategy;
import com.inspur.edp.ai.flow.metadata.AbsNode;
import com.inspur.edp.ai.flow.metadata.Parameter;
import com.inspur.edp.ai.flow.spi.NodeExecuteResult;
import com.inspur.edp.ai.flow.spi.NodeExecutor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizhaorui
 * @date 2025/9/12
 * @description
 */
public class StartNodeExecutor implements NodeExecutor {

    @Override
    public String getKind() {
        return StartNode.KIND;
    }

    @Override
    public NodeExecuteResult execute(FlowContext context, AbsNode node, Map<String, Object> args) {
        Object paramObjects = args.get(StartNode.KIND);
        List<Object> paramValues = (List<Object>) paramObjects;
        List<Parameter> inputParameters = node.getInputParams();
        Map<String, Object> outputObjects = new HashMap<>();
        StartNode startNode = (StartNode) node;
        if (inputParameters != null) {
            int index = 0;
            for (Parameter inputParameter : inputParameters) {
                if (paramValues != null && paramValues.size() > index) {
                    Object value = paramValues.get(index);
                    if (value instanceof JsonNode) {
                        if (!inputParameter.isCustomType()) {
                            value = startNode.getInputDeserializers().get(index).deserialize((JsonNode) value);
                        }
                    }
                    outputObjects.put(inputParameter.getCode(), value);
                }
                index++;
            }
        }
        NodeExecuteResult nodeExecuteResult = new NodeExecuteResult();
        nodeExecuteResult.setVariablesToAdd(outputObjects);
        DefaultFlowStrategy strategy = new DefaultFlowStrategy(node.getId(), node.getOutputPorts().get(0));
        nodeExecuteResult.setFlowStrategy(strategy);
        return nodeExecuteResult;
    }

}